#include "mangamanagerbd.h"

MangaManagerBD::MangaManagerBD()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");

    QStringList s = m_db.drivers();
    m_db.setHostName(hostname);
    m_db.setUserName(user);
    m_db.setPassword(pswd);
    m_db.setDatabaseName(DBName);
    m_valid = m_db.open();
    m_list = new MangaList();
}
MangaManagerBD::~MangaManagerBD()
{
    if(m_valid)
    {
	m_db.close();
	QSqlDatabase::removeDatabase(m_db.connectionName());
    }
    delete m_list;
}
ResourceList * MangaManagerBD::getResources()
{
    QSqlQuery query;
    if(query.exec("SELECT m.id,m.nom,m.adresse from manga m"))
    {
	m_list->clearList();
	while(query.next())
	{
	    m_list->append(new Manga(query.value(4).toInt(),query.value(5).toString(),query.value(6).toString()));
	}
	return m_list;
    }
    else
    {
	return 0;
    }
}
bool MangaManagerBD::addResource(Resource * r)
{
    QSqlQuery query;
    query.prepare("INSERT INTO manga(nom,adresse) VALUES(?,?)");
    query.addBindValue(((Manga*)r)->nom());
    query.addBindValue(((Manga*)r)->adresse());
    if(query.exec())
    {
	QSqlQuery qr2;
	qr2.exec("SELECT LAST_INSERT_ID()");
	qr2.next();
	r->setId(qr2.value(0).toInt());
	return true;
    }
    return false;
}
bool MangaManagerBD::updateResource(Resource * r)
{
    QSqlQuery query;
    query.prepare("UPDATE manga SET nom=?,adresse=? where id=?");
    query.addBindValue(((Manga*)r)->nom());
    query.addBindValue(((Manga*)r)->adresse());
    query.addBindValue(r->getId());
    return query.exec();
}
bool MangaManagerBD::deleteResource(Resource * r)
{
    QSqlQuery query;
    query.prepare("DELETE FROM manga where id=?");
    query.addBindValue(r->getId());
    return query.exec();
}
QString MangaManagerBD::getLastError()
{
    return m_db.lastError().text();
}
